package day16.test04;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Xiao
 * @date 2021/8/10
 */
public class Test04 {
    /**
     * 4. 已知一个Person类,使用反射技术完成以下需求：
     *       1. 创建Person对象
     *       2. 给name属性赋值
     *       3. 调用eat方法和getName方法
     */
    public static void main(String[] args) throws
            ClassNotFoundException,
            NoSuchMethodException,
            InvocationTargetException,
            InstantiationException,
            IllegalAccessException,
            NoSuchFieldException {
        //获取Class对象
        Class<?> clazz = Class.forName("day16.test04.Person");
        //1. 利用Constructor创建Person对象
        Constructor<?> con = clazz.getDeclaredConstructor(int.class);
        con.setAccessible(true);
        Person p = (Person) con.newInstance(24);
        //2. 给name属性赋值
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(p, "阿良");
        //3. 调用eat方法和getName方法
        Method eat = clazz.getMethod("eat", String.class);
        eat.invoke(p, "对象");
        Method getName = clazz.getDeclaredMethod("getName");
        getName.setAccessible(true);
        //输出结果
        String personName = (String) getName.invoke(p);
        System.out.println(personName + ", " + p.age + "岁。。。");
    }
}
